package com.example.shardingjdbctest.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.jdbc.datasource.AbstractDataSource;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Map;

/**
 * @author：kangxuan
 * @date：2024/10/17 4:41 PM
 * @desc:
 */
public class MyDataSource extends AbstractDataSource {
    private Map<String, DataSource> dataSourceMap;
    public MyDataSource(Map<String, DataSource> dataSourceMap) {
        this.dataSourceMap = dataSourceMap;
        for (Map.Entry<String, DataSource> stringDataSourceEntry : dataSourceMap.entrySet()) {
            DataSource value = stringDataSourceEntry.getValue();

        }
    }

    public Map<String, DataSource> getDataSourceMap() {
        return dataSourceMap;
    }

    public void setDataSourceMap(Map<String, DataSource> dataSourceMap) {
        this.dataSourceMap = dataSourceMap;
    }

    public MyDataSource() {
    }

    @Override
    public Connection getConnection() throws SQLException {
        DataSource next = dataSourceMap.values().iterator().next();
        // 创建Enhancer对象
        Enhancer enhancer = new Enhancer();
        // 设置Enhancer的超类（被代理类）
        enhancer.setSuperclass(MyConnection.class);
        // 设置回调，这里使用FixedValue作为回调，它总是返回一个固定值
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                return methodProxy.invokeSuper(obj, args);
            }
        });

        // 创建代理对象
        MyConnection proxy = (MyConnection) enhancer.create();
        proxy.setDataSource((DruidDataSource) next);
        System.out.println("1：getConnection");
        return proxy;
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }
}
